package com.demo.auth.common.service;

import com.demo.api.system.service.RemoteUserService;
import com.demo.common.core.constants.UserConstants;
import com.demo.common.core.enums.UserStatus;
import com.demo.common.core.exception.ServiceException;
import com.demo.common.core.result.R;
import com.demo.common.core.text.Convert;
import com.demo.common.core.utils.StringUtils;
import com.demo.common.core.utils.format.FormatUtils;
import com.demo.common.core.utils.format.PwdCheckUtil;
import com.demo.common.core.utils.ip.IpUtils;
import com.demo.common.redis.constants.CacheConstants;
import com.demo.common.redis.service.RedisService;
import com.demo.common.core.constants.SecurityConstants;
import com.demo.common.core.domain.LoginUser;
import com.demo.common.core.domain.SysUserBo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author MyPC
 */
@Component
public class AuthLogRegService {

    @Autowired
    private RemoteUserService remoteUserService;

    @Autowired
    private SysPasswordService passwordService;

    @Autowired
    private RedisService redisService;

    public LoginUser login(String ak, String pk, String ck, String ckId) {
        boolean verifyCode = Boolean.parseBoolean(remoteUserService.getConfigInfo("sys:account:captchaEnabled", SecurityConstants.INNER).getData());
        // 验证码开关
        if (verifyCode) {
            validateCaptcha(ck, ckId);
        }
        // IP黑名单校验
        String blackStr = Convert.toStr(redisService.getCacheObject(CacheConstants.SYS_LOGIN_BLACKIPLIST));
        if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
            throw new ServiceException("很遗憾，访问IP已被列入系统黑名单");
        }
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(ak, pk)) {
            throw new ServiceException("用户/密码必须填写");
        }
        R<LoginUser> userResult = null;
        if (FormatUtils.isMobile(ak)) {
            userResult = remoteUserService.getUserInfoByMobile(ak, false, SecurityConstants.INNER);
        } else if (FormatUtils.isMailbox(ak)) {
            userResult = remoteUserService.getUserInfoByMailbox(ak, false, SecurityConstants.INNER);
        } else {
            userResult = remoteUserService.getUserInfoByUk(ak, SecurityConstants.INNER);
        }
        if (StringUtils.isNull(userResult) || StringUtils.isNull(userResult.getData())) {
            throw new ServiceException("登录账号：" + ak + " 不存在");
        }
        if (R.FAIL == userResult.getCode()) {
            throw new ServiceException(userResult.getMsg());
        }

        LoginUser loginUser = userResult.getData();
        SysUserBo user = loginUser.getSysUserBo();
        if (UserStatus.DISABLE.getCode().equals(user.getStatus())) {
            throw new ServiceException("对不起，您的账号：" + ak + " 已停用");
        }
        passwordService.validate(user, ak, pk);
        return loginUser;
    }

    public void validateCaptcha(String code, String uuid) {
        String verifyKey = CacheConstants.CAPTCHA_CODE_KEY + StringUtils.nvl(uuid, "");
        String captcha = redisService.getCacheObject(verifyKey);
        redisService.deleteObject(verifyKey);
        if (StringUtils.isEmpty(captcha)) {
            throw new ServiceException("验证码已失效");
        }
        if (!code.equalsIgnoreCase(captcha)) {
            throw new ServiceException("验证码错误");
        }
    }

    /**
     * 注册
     *
     * @param uk
     * @param pk
     * @param cpk
     */
    public void register(String uk, String pk, String cpk) {
        // 用户名或密码为空 错误
        if (StringUtils.isAnyBlank(uk, pk, cpk)) {
            throw new ServiceException("用户/密码必须填写");
        }
        if (FormatUtils.isMobile(uk)) {
            throw new ServiceException("用户名不能为手机号格式！");
        }
        if (FormatUtils.isMailbox(uk)) {
            throw new ServiceException("用户名不能为邮箱格式！");
        }
        if (!pk.equals(cpk)) {
            throw new ServiceException("两次密码输入不一致");
        }
        if (uk.length() < UserConstants.USERNAME_MIN_LENGTH
                || uk.length() > UserConstants.USERNAME_MAX_LENGTH) {
            throw new ServiceException("账户长度必须在2到20个字符之间");
        }
        //校验密码强度
        String pkStrength = remoteUserService.getConfigInfo("sys:pwd:strength", SecurityConstants.INNER).getData();
        PwdCheckUtil.checkStrongPwd(pk, pkStrength);
        // 注册用户信息
        R<?> registerResult = remoteUserService.registerUserInfo(uk, pk, SecurityConstants.INNER);
        if (R.FAIL == registerResult.getCode()) {
            throw new ServiceException(registerResult.getMsg());
        }
    }
}
